
package com.lt.test.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lt.test.api.KtPurchaseOrderService;
import com.lt.test.common.exception.CustomException;
import com.lt.test.common.util.DateUtil;
import com.lt.test.common.util.StringUtils;
import com.lt.test.provider.dao.*;
import com.lt.test.entity.DTO.PageDTO;
import com.lt.test.entity.QueryModel.PageFilter;
import com.lt.test.provider.mapper.SupplierMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service(version = "1.0.0")
public class KtPurchaseOrderServiceImpl implements KtPurchaseOrderService {

	@Resource
	KtPurchaseOrderDao ktPurchaseOrderDao;

	@Resource
	KtPurchaseOrderItemDao ktPurchaseOrderItemDao;

	@Autowired
	SupplierMapper supplierMapper;

	@Resource
	KtRepertoryProdStockDao ktRepertoryProdStockDao;

	@Resource
	KtZoneDao ktZoneDao;

	@Resource
	KtShopRequireOrderDao ktShopRequireOrderDao;

	@Resource
	KtShopRequireOrderItemDao ktShopRequireOrderItemDao;

	@Resource
	KtShopOutstockOrderDao ktShopOutstockOrderDao;

	@Resource
	KtShopOutstockOrderItemDao ktShopOutstockOrderItemDao;

	@Resource
	private KtShopInstockOrderDao ktShopInstockOrderDao;

	@Resource
	private KtShopInstockOrderItemDao ktShopInstockOrderItemDao;

	@Resource
	private KtOtherDao ktOtherDao;


	@Override
	public PageDTO<Map<String, Object>> getPurchaseListByPage(Map parameter) {
		// TODO Auto-generated method stub
		Integer page = Integer.valueOf(parameter.get("page").toString());
		Integer pageSize = Integer.valueOf(parameter.get("rows").toString());
		String filters = parameter.get("filters") == null ? null : parameter.get("filters").toString();
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		List<Map<String,Object>> infoList = null;
		int recordCount = 0;
		String type = null;
		String beginTime = null;
		String endTime = null;
		String approveFlag = null;
		String repertoryId = "";

		String shopName = null;
		String supplierName = null;

		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("type".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					type =  result.getString("data");
				}
				if("beginTime".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					beginTime =  result.getString("data");
				}
				if("endTime".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					endTime =  result.getString("data");
				}
				if("approveFlag".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					approveFlag =  result.getString("data");
				}
				if("repertoryId".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					String repertoryIdstring=  result.getString("data");
					String[] repertoryIds = repertoryIdstring.split(",");
					for (int r = 0; r < repertoryIds.length; r++){
						String str = repertoryIds[r];
						System.out.println(repertoryIds.length);
						if(repertoryIds.length == 1){
							repertoryId = "'" + str + "'";
							break;
						}
						if(r < repertoryIds.length - 1) {
							if(repertoryId.equals("")) {
								repertoryId = "'" + str;
							}else {
								repertoryId = repertoryId + "','" + str;
							}
						}else {
							repertoryId = repertoryId + "','" + str + "'";
						}
					}
				}
				if("shopName".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					shopName =  result.getString("data");
				}
				if("supplierName".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					supplierName =  result.getString("data");
				}
			}
		}
		infoList = ktPurchaseOrderDao.getPurchaseOrderListByPage(type,beginTime, endTime,approveFlag, beginNum, endNum,repertoryId, shopName, supplierName);
		recordCount = Integer.valueOf(ktPurchaseOrderDao.getPurchaseOrderListSize(type,beginTime, endTime,approveFlag, repertoryId, shopName, supplierName).get("total").toString());
		PageDTO<Map<String,Object>> result = new PageDTO<>(page, pageSize, infoList, recordCount);
		return result;
	}

	@Override
	public List<Map<String, Object>> getPurchaseItems(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id").toString();
		return ktPurchaseOrderItemDao.getPurchaseOrderItems(id);
	}

	/**
	 * 修改是调用
	 * 通过Id 获取全部数据
	 * @param parameter
	 * @return
	 */
	public Map findById(String id){
		return supplierMapper.findById(id);
	}

	@Override
	public PageDTO<Map<String, Object>> getSupplierListByPage(Map parameter) {
		// TODO Auto-generated method stub
		Integer page = Integer.valueOf(parameter.get("page").toString());
		Integer pageSize = Integer.valueOf(parameter.get("rows").toString());
		String filters = parameter.get("filters") == null ? null : parameter.get("filters").toString();
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		List<Map<String,Object>> infoList = null;
		int recordCount = 0;
		String supplierName = null;
		String helpCode = null;

		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			List<PageFilter> filterList = new ArrayList<>();
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("supplierName".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					supplierName =  result.getString("data");
				}
				if("helpCode".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					helpCode =  result.getString("data");
				}
			}
		}
		parameter.put("supplierName", supplierName);
		parameter.put("helpCode", helpCode);
		parameter.put("beginNum", beginNum);
		parameter.put("endNum", endNum);
		infoList = supplierMapper.getSupplierListByPage(parameter);
		recordCount = supplierMapper.getSupplierListSize(parameter);
		PageDTO<Map<String,Object>> result = new PageDTO<>(page, pageSize, infoList, recordCount);
		return result;
	}

	@Override
	public void saveSupplier(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id") == null ? null : parameter.get("id").toString();
		String userId = parameter.get("operator").toString();
		if(StringUtils.isNullOrEmpty(id)){
			parameter.put("id", StringUtils.getUUID());
			parameter.put("createTime", new Date());
			parameter.put("createUser", userId);
			supplierMapper.createKtSupplier(parameter);
		}else{
			parameter.put("modifyTime", new Date());
			parameter.put("modifyUser", userId);
			supplierMapper.updateKtSupplier(parameter);
		}
	}

	/**
	 * 删除时调用
	 * 通过Id 获取全部数据
	 * @param id
	 * @return
	 */
	@Override
	public int deleteSupplier(String id) {
		return supplierMapper.deleteKtSupplier(id);
	}


	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void savePurchaseOrder(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id") == null ? null : parameter.get("id").toString();
		String repertoryId = parameter.get("repertoryId") == null ? null : parameter.get("repertoryId").toString();
		String userId = parameter.get("operator").toString();
		if(StringUtils.isNullOrEmpty(id)){
			id = StringUtils.getUUID();
			parameter.put("state", "1");
			parameter.put("id", id);
			parameter.put("createUser", userId);
			parameter.put("createTime", new Date());
			ktPurchaseOrderDao.create(parameter);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("purchaseId", id);
				orderItem.put("repertoryId", repertoryId);
				orderItem.put("createTime", new Date());
				orderItem.put("state", "1");
				orderItemList.add(orderItem);
			}
			ktPurchaseOrderItemDao.batch(orderItemList);
		}else{
			ktPurchaseOrderDao.update(parameter);
			ktPurchaseOrderItemDao.deletePurchaseOrderItem(id);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("purchaseId", id);
				orderItem.put("repertoryId", repertoryId);
				orderItem.put("createTime", new Date());
				orderItem.put("state", "1");
				orderItemList.add(orderItem);
			}
			ktPurchaseOrderItemDao.batch(orderItemList);

		}


		String prodList = parameter.get("prodList").toString();
		JSONArray dataArray = JSONArray.fromObject(prodList);
		List<Map> orderItemList = new ArrayList<Map>();
		List<String> requireIdList = new ArrayList<String>();
		String temRequireId = null;
		for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
			JSONObject obj = dataArray.getJSONObject(i);
			if(obj.get("requireId") != null){
				String requireId = obj.getString("requireId");
				if(!requireId.equals(temRequireId)){
					temRequireId = requireId;
					requireIdList.add(requireId);
				}
				String requireOrderItemId = obj.getString("requireOrderItemId");
				Map orderItem = new HashMap();
				orderItem.put("id", requireOrderItemId);
				orderItem.put("status", obj.getString("type"));
				orderItem.put("state", "1");
				orderItemList.add(orderItem);
			}
		}

		if(requireIdList.size() > 0){
			ktShopRequireOrderItemDao.batchUpdate(orderItemList);
			for (int i = 0; i < requireIdList.size(); i++) {
				List<Map<String,Object>> unFinishRequireOrderItems  = ktShopRequireOrderItemDao.getUnFinishShopRequireOrderItems(requireIdList.get(i));
				if(unFinishRequireOrderItems.size()==0){
					Map map = new HashMap();
					map.put("id", requireIdList.get(i));
					map.put("state", "1");
					ktShopRequireOrderDao.update(map);
				}
			}

		}

	}

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void purchaseOrderCheck(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id").toString();
		String userId = parameter.get("operator").toString();
		String approveFlag = parameter.get("approveFlag").toString();
		parameter.put("status", "1");
		parameter.put("modifyUser", userId);
		parameter.put("modifyTime", new Date());
		ktPurchaseOrderDao.update(parameter);
		ktPurchaseOrderItemDao.updateOrderItemApproveFlag(id, approveFlag);
//		ktRepertoryProdStockDao.updateStockByPurchaseId(id);
	}



	@Override
	public PageDTO<Map<String, Object>> getShopRequireOrderListByPage(Map parameter) {
		// TODO Auto-generated method stub
		Integer page = Integer.valueOf(parameter.get("page").toString());
		Integer pageSize = Integer.valueOf(parameter.get("rows").toString());
		String filters = parameter.get("filters") == null ? null : parameter.get("filters").toString();
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		List<Map<String,Object>> infoList = null;
		int recordCount = 0;

		String id = null;
		String remark = null;
		String shopId = "";
		String createUser = null;
		String approveFlag = null;
		String beginDate = null;
		String endDate = null;
		String type = null;
		String state = null;
		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("id".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					id =  result.getString("data");
				}
				if("remark".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					remark =  result.getString("data");
				}
				if("shopId".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
//					shopId =  result.getString("data");
					String shopIdstring=  result.getString("data");
					String[] shopIds = shopIdstring.split(",");
					for (int r = 0; r < shopIds.length; r++){
						String str = shopIds[r];
						System.out.println(shopIds.length);
						if(shopIds.length == 1){
							shopId = "'" + str + "'";
							break;
						}
						if(r < shopIds.length - 1) {
							if(shopId.equals("")) {
								shopId = "'" + str;
							}else {
								shopId = shopId + "','" + str;
							}
						}else {
							shopId = shopId + "','" + str + "'";
						}
					}
				}

				if("createUser".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					createUser =  result.getString("data");
				}
				if("approveFlag".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					approveFlag =  result.getString("data");
				}
				if("beginDate".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					beginDate =  result.getString("data");
				}
				if("endDate".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					endDate =  result.getString("data");
				}
				if("type".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					type =  result.getString("data");
				}
				if("state".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					state =  result.getString("data");
				}
			}
		}
		if(StringUtils.isNullOrEmpty(beginDate)){
			beginDate = "2018-01-01";
		}
		if(StringUtils.isNullOrEmpty(endDate)){
			endDate = "2019-01-01";
		}
		infoList = ktShopRequireOrderDao.getPurchaseOrderListByPage(type,id, createUser, shopId, remark, approveFlag, beginDate, endDate, beginNum, endNum, state);
		recordCount = Integer.valueOf(ktShopRequireOrderDao.getPurchaseOrderListSize(type,id, createUser, shopId, remark, approveFlag, beginDate, endDate, state).get("total").toString());
		PageDTO<Map<String,Object>> result = new PageDTO<>(page, pageSize, infoList, recordCount);
		return result;
	}

	@Override
	public List<Map<String, Object>> getShopRequireOrderItems(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id").toString();
		return ktShopRequireOrderItemDao.getShopRequireOrderItems(id);
	}

	@Override
	public int upShopRequireOrderItems(Map parameter) {
		return ktShopRequireOrderItemDao.update(parameter);
	}

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void saveShopRequireOrder(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id") == null ? null : parameter.get("id").toString();
		String userId = parameter.get("operator").toString();
		String shopId = parameter.get("shopId") == null ? "1" : parameter.get("shopId").toString();

		//验证调拨转换  调拨方改成出库方
		String allot = parameter.get("allot") == null ? "" : parameter.get("allot").toString();
		String requireShopId = parameter.get("requireShopId") == null ? "" : parameter.get("requireShopId").toString();
		if(StringUtils.isNullOrEmpty(id)){
			id = StringUtils.getUUID();
			parameter.put("state", "2");
			parameter.put("createUser", userId);
			parameter.put("createTime", new Date());
			parameter.put("id", id);
			ktShopRequireOrderDao.create(parameter);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("requireId", id);
				orderItem.put("shopId", shopId);
				orderItem.put("stateDate", new Date());
				orderItemList.add(orderItem);
			}
			ktShopRequireOrderItemDao.batch(orderItemList);
		}else{
			ktShopRequireOrderDao.update(parameter);
			ktShopRequireOrderItemDao.deleShopRequireOrderItem(id);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("requireId", id);
				orderItem.put("shopId", shopId);
				orderItem.put("stateDate", new Date());
				orderItemList.add(orderItem);
			}
			ktShopRequireOrderItemDao.batch(orderItemList);
		}
		if(!allot.equals("")) {
			Map map = new HashMap();
			map.put("id", id);
			map.put("shopId", requireShopId);
			ktShopRequireOrderDao.update(map);
		}
	}

	@Override
	public void shopRequireOrderCheck(Map parameter) {
		// TODO Auto-generated method stub
		ktShopRequireOrderDao.update(parameter);

	}

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void shopConfirmDeliverOrder(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id").toString();
		ktShopRequireOrderItemDao.updateStockByRequireId(id);

		Date now = new Date();
		String instockNo = "RK" + "KT"
				+ DateUtil.formatDate(new Date(), "yyyyMMddHHmmss");
		ktShopRequireOrderItemDao.saveShopInstock(instockNo,id);
		ktShopRequireOrderItemDao.saveShopInstockItem(instockNo, id);
	}


	@Override
	public PageDTO<Map<String, Object>> getShopOutstockOrderListByPage(Map parameter) {
		// TODO Auto-generated method stub
		Integer page = Integer.valueOf(parameter.get("page").toString());
		Integer pageSize = Integer.valueOf(parameter.get("rows").toString());
		String filters = parameter.get("filters") == null ? null : parameter.get("filters").toString();
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		List<Map<String,Object>> infoList = null;
		int recordCount = 0;

		String id = null;
		String remark = null;
		String shopId = "";
		String createUser = null;
		String approveFlag = null;
		String beginDate = null;
		String endDate = null;
		String type = null;

		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("id".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					id =  result.getString("data");
				}
				if("remark".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					remark =  result.getString("data");
				}
				if("shopId".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
//					shopId =  result.getString("data");
					String shopIdstring=  result.getString("data");
					String[] shopIds = shopIdstring.split(",");
					for (int r = 0; r < shopIds.length; r++){
						String str = shopIds[r];
						System.out.println(shopIds.length);
						if(shopIds.length == 1){
							shopId = "'" + str + "'";
							break;
						}
						if(r < shopIds.length - 1) {
							if(shopId.equals("")) {
								shopId = "'" + str;
							}else {
								shopId = shopId + "','" + str;
							}
						}else {
							shopId = shopId + "','" + str + "'";
						}
					}
				}
				if("createUser".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					createUser =  result.getString("data");
				}
				if("approveFlag".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					approveFlag =  result.getString("data");
				}
				if("beginDate".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					beginDate =  result.getString("data");
				}
				if("endDate".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					endDate =  result.getString("data");
				}
				if("type".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					type =  result.getString("data");
				}
			}
		}
		infoList = ktShopOutstockOrderDao.getOutstockOrderListByPage(id, createUser, shopId, remark, approveFlag, beginDate, endDate, beginNum, endNum, type);
		recordCount = Integer.valueOf(ktShopOutstockOrderDao.getOutstockOrderListSize(id, createUser, shopId, remark, approveFlag, beginDate, endDate, type).get("total").toString());
		PageDTO<Map<String,Object>> result = new PageDTO<>(page, pageSize, infoList, recordCount);
		return result;
	}

	@Override
	public List<Map<String, Object>> getShopOutstockOrderItems(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id").toString();
		return ktShopOutstockOrderItemDao.getShopOutstockOrderItems(id);
	}

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void saveShopOutstockOrder(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id") == null ? null : parameter.get("id").toString();
		String shopId = parameter.get("shopId") == null ? null: parameter.get("shopId").toString();
		String type = parameter.get("type").toString();
		List<Map> purchaseOrderItemList = new ArrayList<Map>();
		if(StringUtils.isNullOrEmpty(id)){
			id = StringUtils.getUUID();
			parameter.put("state", "1");
			parameter.put("createTime", new Date());
			parameter.put("id", id);
			ktShopOutstockOrderDao.create(parameter);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("outstockId", id);
//				orderItem.put("shopId", obj.getString("requireShopId"));
//				orderItem.put("requireShopId", obj.getString("shopId"));
				orderItem.put("stateDate", new Date());
				orderItem.put("realQuantity", obj.getString("quantity"));
				orderItemList.add(orderItem);
				if("8".equals(type) || "9".equals(type) || "10".equals(type)){
					if(obj.get("purchaseOrderItemId") != null){
						Map purchaseOrderItem = new HashMap();
						purchaseOrderItem.put("id", obj.getString("purchaseOrderItemId"));
						purchaseOrderItem.put("type", parameter.get("type"));
						purchaseOrderItemList.add(purchaseOrderItem);
					}

				}
			}
			ktShopOutstockOrderItemDao.batch(orderItemList);
		}else{
			ktShopOutstockOrderDao.update(parameter);
			ktShopOutstockOrderItemDao.deleShopOutstockOrderItem(id);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("outstockId", id);
				orderItem.put("shopId", shopId);
				orderItem.put("stateDate", new Date());
				orderItemList.add(orderItem);
				if("8".equals(type) || "9".equals(type) || "10".equals(type)){
					if(obj.get("purchaseOrderItemId") != null){
						Map purchaseOrderItem = new HashMap();
						purchaseOrderItem.put("id", obj.getString("purchaseOrderItemId"));
						purchaseOrderItem.put("type", parameter.get("type"));
						purchaseOrderItemList.add(purchaseOrderItem);
					}
				}
			}
			ktShopOutstockOrderItemDao.batch(orderItemList);
		}

		if("8".equals(type) || "9".equals(type) || "10".equals(type) ){
			if(purchaseOrderItemList.size()>0){
				ktPurchaseOrderItemDao.batchUpdate(purchaseOrderItemList);
				String purchaseId = parameter.get("batchNo").toString();
				String requireShopId = parameter.get("requireShopId") == null ? "" : parameter.get("requireShopId").toString();
				List<Map<String,Object>> unFinishRequireOrderItems  = ktPurchaseOrderItemDao.getUnFinishPurchaseOrderItems(purchaseId);
				if(unFinishRequireOrderItems.size()==0){
					Map map = new HashMap();
					map.put("id", purchaseId);
					map.put("supplierId",requireShopId);
					map.put("approveFlag", "1");
					map.put("state", "1");
					map.put("type", type);
					ktPurchaseOrderDao.update(map);
				}
			}

		}
	}

	@Override
	public void shopOutstockOrderCheck(Map parameter) {
		// TODO Auto-generated method stub
		parameter.put("approveTime", new Date());
		ktShopOutstockOrderDao.update(parameter);
	}

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void shopConfirmOutstockOrder(Map parameter) throws CustomException {
		// TODO Auto-generated method stub
		String id = parameter.get("id").toString();
		Map<String,Object> record = ktShopOutstockOrderDao.getRecord(id);
		if(record != null){
			throw new CustomException("该订单已被操作!");
		}
		//查询出库有没有负数的
		List<Map<String,Object>> stockLessThanZeroList = ktOtherDao.getStockLessThanZeroList(id);
		if(stockLessThanZeroList.size()>0){
			throw new CustomException("该订单库存不足!");
		}

		String userId = parameter.get("operator") == null ? null : parameter.get("operator").toString();
		parameter.put("approveFlag", "1");
		parameter.put("approveUser", userId);
		parameter.put("approveTime", new Date());
		parameter.put("status", "1");
		ktShopOutstockOrderDao.update(parameter);
		ktShopOutstockOrderItemDao.updateStockByOutstockId(id);
		ktPurchaseOrderItemDao.rewriteRealOutstockQuantity(id);


	}

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void createInOutStockOrder(Map parameter) throws CustomException{
		// TODO Auto-generated method stub
		String requireId = parameter.get("requireId").toString();
		String type = parameter.get("type").toString();
		String shopId = parameter.get("shopId").toString();
		String requireShopId = parameter.get("requireShopId").toString();

		Map<String,Object> record = ktShopRequireOrderDao.getRecord(requireId);
		if(record != null){
			throw new CustomException("该订单已被操作!");
		}

		parameter.put("batchNo", requireId);
		parameter.put("shopId", requireShopId);
		parameter.put("requireShopId", shopId);
		Map data = new HashMap();
		data.putAll(parameter);
		data.put("shopId", shopId);
		data.put("requireShopId", requireShopId);



		String prodList = parameter.get("prodList").toString();
		JSONArray dataArray = JSONArray.fromObject(prodList);
		List<Map> orderItemList = new ArrayList<Map>();
		for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
			JSONObject obj = dataArray.getJSONObject(i);

			String tempShopId = obj.getString("shopId");
			obj.put("shopId", obj.getString("requireShopId"));
			obj.put("requireShopId", tempShopId);
			if("2".equals(type) || "6".equals(type)){
				Map orderItem = new HashMap();
				orderItem.put("id", obj.getString("requireOrderItemId"));
				orderItem.put("status", parameter.get("type"));
				orderItem.put("state", "1");
				orderItemList.add(orderItem);
			}

		}
		parameter.put("prodList", dataArray.toString());

		saveShopOutstockOrder(parameter);
		saveShopInstockOrder(data);


		if("2".equals(type) || "6".equals(type)){

			ktShopRequireOrderItemDao.batchUpdate(orderItemList);

			List<Map<String,Object>> unFinishRequireOrderItems  = ktShopRequireOrderItemDao.getUnFinishShopRequireOrderItems(requireId);
			if(unFinishRequireOrderItems.size()==0){
				Map map = new HashMap();
				map.put("id", requireId);
				map.put("state", "1");
				ktShopRequireOrderDao.update(map);
			}
		}

	}

	@Override
	public PageDTO<Map<String, Object>> getShopInstockOrderListByPage(Map parameter) {
		// TODO Auto-generated method stub
		Integer page = Integer.valueOf(parameter.get("page").toString());
		Integer pageSize = Integer.valueOf(parameter.get("rows").toString());
		String filters = parameter.get("filters") == null ? null : parameter.get("filters").toString();
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		List<Map<String,Object>> infoList = null;
		int recordCount = 0;

		String id = null;
		String remark = null;
		String shopId = "";
		String createUser = null;
		String approveFlag = null;
		String beginDate = null;
		String endDate = null;
		String type = null;

		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("id".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					id =  result.getString("data");
				}
				if("remark".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					remark =  result.getString("data");
				}
				if("shopId".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
//					shopId =  result.getString("data");
					String shopIdstring=  result.getString("data");
					String[] shopIds = shopIdstring.split(",");
					for (int r = 0; r < shopIds.length; r++){
						String str = shopIds[r];
						System.out.println(shopIds.length);
						if(shopIds.length == 1){
							shopId = "'" + str + "'";
							break;
						}
						if(r < shopIds.length - 1) {
							if(shopId.equals("")) {
								shopId = "'" + str;
							}else {
								shopId = shopId + "','" + str;
							}
						}else {
							shopId = shopId + "','" + str + "'";
						}
					}
				}
				if("createUser".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					createUser =  result.getString("data");
				}
				if("approveFlag".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					approveFlag =  result.getString("data");
				}
				if("beginDate".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					beginDate =  result.getString("data");
				}
				if("endDate".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					endDate =  result.getString("data");
				}
				if("type".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					type =  result.getString("data");
				}
			}
		}
		infoList = ktShopInstockOrderDao.getInstockOrderListByPage(id, createUser, shopId, remark, approveFlag, beginDate, endDate, beginNum, endNum, type);

		recordCount = Integer.valueOf(ktShopInstockOrderDao.getInstockOrderListSize(id, createUser, shopId, remark, approveFlag, beginDate, endDate, type).get("total").toString());
		PageDTO<Map<String,Object>> result = new PageDTO<>(page, pageSize, infoList, recordCount);
		return result;
	}

	@Override
	public List<Map<String, Object>> getShopInstockOrderItems(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id").toString();
		String type = parameter.get("type") == null ? "" : parameter.get("type").toString();
		if(type.equals("20")){
			return ktShopInstockOrderItemDao.getShopAppInstockOrderItems(id);
		}else {
			return ktShopInstockOrderItemDao.getShopInstockOrderItems(id);
		}
	}

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void saveShopInstockOrder(Map parameter) {
		// TODO Auto-generated method stub
		System.out.println("=======》入库数据："+parameter);
		String id = parameter.get("id") == null ? null : parameter.get("id").toString();
		String shopId = parameter.get("shopId") == null ? null : parameter.get("shopId").toString();
		if(StringUtils.isNullOrEmpty(id)){
			id = StringUtils.getUUID();
			parameter.put("state", "1");
			parameter.put("createTime", new Date());
			parameter.put("id", id);
			ktShopInstockOrderDao.create(parameter);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				String creationDate = obj.get("creationDate") == null ? "" : obj.get("creationDate").toString();
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("instockId", id);
				orderItem.put("shopId", shopId);
				orderItem.put("stateDate", new Date());
				orderItem.put("realQuantity", obj.getString("quantity"));
				if(!creationDate.equals("")) {
					orderItem.put("creationDate", creationDate);
				}
				orderItemList.add(orderItem);
			}
			ktShopInstockOrderItemDao.batch(orderItemList);
		}else{
			ktShopInstockOrderDao.update(parameter);
			ktShopInstockOrderItemDao.deleShopInstockOrderItem(id);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("instockId", id);
				orderItem.put("shopId", obj.getString("shopId"));
				orderItem.put("stateDate", new Date());
				orderItemList.add(orderItem);
			}
			ktShopInstockOrderItemDao.batch(orderItemList);
		}
	}

	@Override
	public void shopInstockOrderCheck(Map parameter) {
		// TODO Auto-generated method stub
		String type = parameter.get("type") == null ? "" : parameter.get("type").toString();
		if(type.equals("20")){
			ktShopInstockOrderDao.updateApp(parameter);
		}else {
			parameter.put("approveTime", new Date());
			ktShopInstockOrderDao.update(parameter);
		}
	}

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void shopConfirmInstockOrder(Map parameter) throws CustomException {
		// TODO Auto-generated method stub
		String id = parameter.get("id").toString();
		Map<String,Object> record = ktShopInstockOrderDao.getRecord(id);
		if(record != null){
			throw new CustomException("该订单已被操作!");
		}
		String userId = parameter.get("operator") == null ? null : parameter.get("operator").toString();
		String type = parameter.get("type").toString();
		if("6".equals(type)){
			//调拨入库单查询 调拨出库单是否出库
			Map<String,Object> outStockRecord = ktOtherDao.getOutStockRecordByBatchNo(id);
			if(outStockRecord == null){
				throw new CustomException("该订单对应的出库的未出库!");
			}
		}
		parameter.put("approveFlag", "1");
		parameter.put("approveUser", userId);
		parameter.put("approveTime", new Date());
		parameter.put("status", "1");
		ktShopInstockOrderDao.update(parameter);
		ktShopInstockOrderItemDao.updateStockByInstockId(id);

		//直调入库单 2，调拨入库单6
		if("2".equals(type) || "6".equals(type)){

			List<Map<String,Object>> InstockData = ktOtherDao.getRepairInstock(id);
			if(InstockData.size()>0){
				//入库
				Map instockMap = new HashMap();
				instockMap.put("shopId", InstockData.get(0).get("requireShopId"));
				instockMap.put("requireShopId", InstockData.get(0).get("shopId"));

				//这种会导致batchNo重复,不能添加,如果需要的添加的话,可在后面加_REPAIR
				instockMap.put("batchNo", InstockData.get(0).get("batchNo"));
				if(type.equals("2")){
					instockMap.put("type", "1");
				}else if(type.equals("6")){
					instockMap.put("type", "5");
				}

				instockMap.put("prodList", JSONArray.fromObject(InstockData).toString());

				saveShopInstockOrder(instockMap);

			}
			List<Map<String,Object>> outStockData = ktOtherDao.getRepairOutStock(id);
			if(outStockData.size()>0){
				//出库
				Map outstockMap = new HashMap();
				outstockMap.put("shopId", outStockData.get(0).get("requireShopId"));
				outstockMap.put("requireShopId", outStockData.get(0).get("shopId"));
				outstockMap.put("batchNo", outStockData.get(0).get("batchNo"));
				if(type.equals("2")){
					outstockMap.put("type", "1");
				}else if(type.equals("6")){
					outstockMap.put("type", "5");
				}

				outstockMap.put("prodList", JSONArray.fromObject(outStockData).toString());

				saveShopOutstockOrder(outstockMap);
			}
		}else if("3".equals(type) || "4".equals(type)){
			//如果是采购，回填 实际数量
			ktPurchaseOrderItemDao.rewriteRealquantity(id);
		}else if("7".equals(type)){
			ktPurchaseOrderItemDao.rewriteLossProfitRealquantity(id);
		}

	}



}
